<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\wh\admin;

use app\wh\builder\Admin;
use app\wh\builder\ZBuilder;
use app\wh\model\Material as MaterialModel;
use app\wh\model\Supplier as SupplierModel;
use app\wh\model\StockType as StockTypeModel;
use app\wh\model\MaterialGoods as MaterialGoodsModel;
use app\wh\model\Stock as StockModel;
use app\mill\model\Order as OrderModel;
use app\mill\model\Archives as ArchivesModel;
use app\mill\model\Client as ClientModel;
use app\mill\model\Stat as StatModel;
use app\wh\model\Color as ColorModel;
use form\complexTable\Builder;
use think\Db;
use think\facade\Env;

/**
 * 采购单控制器
 * @package app\admin\controller
 */
class Material extends Admin
{
    public $_type_id = '';
    public $_top_html = '';
    /**
     * 初始化
     * @author 蔡伟明 <314013107@qq.com>
     * @throws \think\Exception
     */
    protected function initialize(){
        parent::initialize();

        $this->_type_id = input('stock_type',input('type_pid'));
        if(empty($this->_type_id))$this->_type_id = StockTypeModel::getTypePidFirst();

        $option = "{
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'shadow'
                            }
                        },
                        legend: {
            
                        },
                        grid: {
                            left: '15',
                            right: '15',
                            bottom: '0',
                            top:'30',
                            containLabel: true
                        },
                        yAxis : [
                            {
                                type : 'value',
                                axisLabel : {
                                    formatter: ''
                                }
                            }
                        ],
                        xAxis: {
                            type: 'category',
                            boundaryGap : false,
                            data: [
                                '油漆(KG)',
                                '粉末(KG)',
                                '木纹(KG)',
                                '色浆(KG)',
                                '铝卷(KG)',
                                '铝板(KG)',
                                '型材(KG)',
                                '化工(KG)',
                                '生产物资',
                                '办公物资',
                            ]
                        },
                        series: [
                          {
                            'name': '总量',
                            'type': 'line',
                            'smooth':true,
                            'data': [
                              150,
                              100,
                              200,
                              140,
                              100,
                              230,
                              138,
                              201,
                              124,
                              116,
                            ],
                            'itemStyle': {
                              'normal': {
                                'label': {
                                  'show': true
                                }
                              }
                            }
                          },
                          {
                            'name': '总额($)',
                            'type': 'line',
                            'smooth':true,
                            'data': [
                              130,
                              40,
                              100,
                              120,
                              80,
                              200,
                              118,
                              141,
                              54,
                              96,
                            ],
                            'itemStyle': {
                              'normal': {
                                'label': {
                                  'show': true
                                }
                              }
                            }
                          }
                        ]
                    }";
        $url = url('mill/stat/ajaxOrder');
        $this->_top_html = StatModel::materialHtml($url,$option,['charts']);
    }
    //首页
    public function index(){
        return $this->fetch('index/index');
    }

    //新增
    public function add($is_add = true)
    {

        $print = input('print',0);
        $id = input('id');
        $ainp_id = input('ainp_id');
        $order_ids = trim(input('order_ids'),',');
        $order_color_ids = trim(input('order_color_ids'),',');
        $not_order_color_ids = trim(input('not_order_color_ids'),',');
        $type_pid = $this->_type_id;
        $is_order_color = input('is_order_color',1);//是否按确认颜色的工程来创建采购单 0:不按工程 1:按工程

        if ($this->request->isPost()) {
            $data = input();

            //要校验的字段
            $validate = [
                'type_id'               =>  '请选择物料类别',
                'supplier_id'           =>  '请选择供应商',
                'material_name'         =>  '请填写物料名称',
                'number'                =>  '请填写需求量',
                'model'                 =>  '请填写规格',
            ];
            if(in_array($type_pid,ColorModel::$type_pid_arr)){
                unset($validate['number']);
                unset($validate['model']);
            }
            elseif($type_pid == 4 || $type_pid == 5){
                $validate['quality'] = '请选择材质';
                $validate['lot_sn'] = '请填写批号';
                $data['status'] = 1;//铝卷跳过审核流程
            }
            /*elseif($type_pid == 5){
                unset($validate['number']);
                unset($validate['supplier_id']);
            }*/
            elseif($type_pid == 6 || $type_pid == 7){
                unset($validate['material_name']);
                $data['status'] = 1;//铝板跳过审核流程
            }
            $lists = MaterialModel::serialize($data['goods'],0,$validate);
            if(!is_array($lists))$this->error($lists);
            unset($data['goods']);

            $data['material_sn'] = MaterialModel::getMaterialSn();//采购单编号
            if(empty($data['create_time']))$data['create_time'] = date('Y-m-d H:i:s');
            $data['create_time'] = strtotime($data['create_time']);
            if(!empty($data['address_time']))$data['address_time'] = strtotime($data['address_time']);
            $data['update_time'] = time();
            if(!empty($id)){

                $info = Db::name('wh_material')->where(['id'=>$id])->find();
                if(in_array($type_pid,ColorModel::$type_pid_arr)){

                    //新数据的color_ids
                    $data_order_color_ids = explode(',',$data['order_color_ids']);
                    //原数据的color_ids
                    $info_order_color_ids = explode(',',$info['order_color_ids']);
                    $old_order_color_ids = '';
                    //遍历，筛选出删掉的color_ids，并更新状态
                    foreach ($info_order_color_ids as $cik=>$civ){
                        if(!in_array($civ,$data_order_color_ids))$old_order_color_ids .= ",{$civ}";
                    }

                    if(!empty($data['order_color_ids']))Db::name('wh_order_color')->where([['id','in',$data['order_color_ids']]])->update(['status'=>2]);
                    if(!empty($old_order_color_ids))Db::name('wh_order_color')->where([['id','in',$old_order_color_ids]])->update(['status'=>1]);
                }

                $data['id'] = $id;
                if($data['status']<0)$data['status'] = 0;
                unset($data['create_time']);
                unset($data['material_sn']);
                $re = MaterialModel::update($data);
                $data['material_sn'] = $info['material_sn'];
            }
            else {
                if(!empty($data['order_color_ids']))Db::name('wh_order_color')->where([['id','in',$data['order_color_ids']]])->update(['status'=>2]);
                if(!empty($old_order_color_ids))Db::name('wh_order_color')->where([['id','in',$old_order_color_ids]])->update(['status'=>1]);
                $re = MaterialModel::create($data);
                $data['id'] = $re['id'];

                //关联预采购单
                if(!empty($ainp_id))Db::name('wh_material_ainp')->where(['id'=>$ainp_id])->update(['material_sn'=>$data['material_sn']]);
            }
            $data['number'] = 0;
            foreach ($lists as &$v){
                if(empty($v['material_name']))$v['material_name'] = $v['model'];
                if(!empty($v['order_id']))$v['archives_sn'] = Db::name('mill_order')->where([['id','=',$v['order_id']]])->value(['archives_sn']);
                //更新库存信息，厂家色号信息
                if(!empty($v['color_sn']) && !empty($data['supplier_color'][$v['color_sn']])){
                    $up_supplier = $data['supplier_color'][$v['color_sn']];

                    //如果供应商有更换，则进行厂家色号更换等处理
                    if($up_supplier['supplier_id'] != $v['supplier_id']){
                        //判断厂家色号是否已录入
                        $color_where = [
                            'model'             =>  $up_supplier['supplier_color'],
                            'supplier_id'       =>  $up_supplier['supplier_id'],
                            'type_id'           =>  $up_supplier['type_id'],
                        ];
                        $supplier_color = Db::name('wh_stock')->where($color_where)->find();

                        $supplier_color_add = [];
                        //替换
                        if($supplier_color){
                            $supplier_color_add['supplier_id'] = $supplier_color['supplier_id'];
                            $supplier_color_add['type_pid'] = $supplier_color['type_pid'];
                            $supplier_color_add['type_id'] = $supplier_color['type_id'];
                            $supplier_color_add['supplier_color'] = $supplier_color['model'];
                            $supplier_color_add['color_type_id'] = $supplier_color['color_type_id'];
                            $supplier_color_add['color_sn'] = $supplier_color['color_sn'];
                            $supplier_color_add['stock_id'] = $supplier_color['id'];
                            $supplier_color_add['stock_sn'] = $supplier_color['stock_sn'];
                            $supplier_color_add['heat'] = $supplier_color['heat'];

                            //重新组装厂家色号信息，采购量等
                            //if(!empty($data['supplier_color'][$supplier_color['color_sn']]))
                        }
                        //新增
                        else{
                            $supplier_color = Db::name('wh_stock')->where(['stock_sn'=>$up_supplier['stock_sn']])->find();

                            //新增厂家颜色
                            unset($supplier_color['id']);
                            $supplier_color['supplier_id'] = $up_supplier['supplier_id'];
                            $supplier_color['color_sn'] = ColorModel::getColorSn($supplier_color['type_id'],$supplier_color['heat']);

                            $supplier_color_add['supplier_id'] = $up_supplier['supplier_id'];
                            $supplier_color_add['type_pid'] = $supplier_color['type_pid'];
                            $supplier_color_add['type_id'] = $supplier_color['type_id'];
                            $supplier_color_add['supplier_color'] = $supplier_color['model'];
                            $supplier_color_add['color_type_id'] = $supplier_color['color_type_id'];
                            $supplier_color_add['color_sn'] = $supplier_color['color_sn'];
                            $supplier_color_add['stock_sn'] = StockModel::getStockSn($supplier_color);
                            $supplier_color_add['stock_id'] = Db::name('wh_stock')->where(['stock_sn'=>$supplier_color_add['stock_sn']])->value('id');
                            $supplier_color_add['heat'] = $supplier_color['heat'];
                        }
                        //厂家色号信息
                        Db::name('wh_order_color')->where([['color_sn','=',$v['color_sn']],['order_id','in',$data['order_ids']]])->update($supplier_color_add);

                        //重置采购单信息
                        $v = array_merge($v,$supplier_color_add);
                        $v['material_name'] = $supplier_color['title'];
                    }

                    //重新分配定量
                    $count = $up_supplier['count'];
                    if($count > 1){
                        $v['number'] = intval($up_supplier['number']/$count);
                        $data['supplier_color'][$up_supplier['color_sn']]['number'] -= $v['number'];
                    }
                    else $v['number'] = $up_supplier['number'];
                    $data['supplier_color'][$up_supplier['color_sn']]['count'] --;
                }
                //如果批号存在，则判断是否有库存，有库存则生成新的库存编号
                if(!empty($v['lot_sn'])){
                    $update_stock = [
                        'lot_sn'    =>  $v['lot_sn'],
                        'model2'    =>  $v['lot_sn'],
                    ];
                    $v['is_where'] = true;
                    $stock_where = StockModel::getStockSn($v);
                    unset($v['is_where']);

                    //如果批号被修改，则更新库存的批号
                    if(!empty($v['id'])){
                        $goods = Db::name('wh_material_goods')->where(['id'=>$v['id']])->find();
                        if($v['lot_sn'] != $goods['lot_sn'])Db::name('wh_stock')->where(['stock_sn'=>$goods['stock_sn']])->update($update_stock);
                    }

                    //获取相同批号的库存，没有则获取没批号的库存
                    $stock = Db::name('wh_stock')->where($stock_where)->where(['model2'=>$v['lot_sn']])->find();
                    if(empty($stock))$stock = Db::name('wh_stock')->where($stock_where)->where(['number'=>0,'model2'=>''])->find();
                    //如果库存 > 0，则生成新库存
                    //如果库存 = 0，且批号不同，则生成新库存
                    //if($stock['number'] > 0 || ($stock['number'] == 0 && $stock['lot_sn'] == '')){
                    //都没有，则生成新的库存
                    if(empty($stock)){
                        $v['model2'] = $v['lot_sn'];
                        $v['stock_sn'] = StockModel::getStockSn($v);
                    }
                    else {
                        $v['stock_sn'] = $stock['stock_sn'];
                    }
                    unset($v['model2']);

                    Db::name('wh_stock')->where(['stock_sn'=>$v['stock_sn']])->update($update_stock);
                }
                else $v['stock_sn'] = StockModel::getStockSn($v);

                //更新库存信息
                Db::name('wh_stock')->where(['stock_sn'=>$v['stock_sn']])->update(['title'=>$v['material_name']]);
                //同步新增同规格不同物料类别的库存
                $stock = Db::name('wh_stock')->where(['stock_sn'=>$v['stock_sn']])->find();
                StockModel::addSameStock($v['stock_sn'],$stock);

                if(!empty($v['id']))MaterialGoodsModel::update($v);
                else {
                    $v['material_id'] = $data['id'];
                    $v['material_sn'] = $data['material_sn'];
                    if(!empty($data['status']))$v['status'] = $data['status'];
                    $v['create_time'] = time();

                    MaterialGoodsModel::create($v);
                }
                $data['number'] += floatval($v['number']);
                $data['supplier_id'] = $v['supplier_id'];
            }

            Db::name('wh_material')->where([['id','in',$data['id']]])->update(['number'=>$data['number'],'supplier_id'=>$data['supplier_id']]);

            if($re)$this->success('操作成功', cookie('__forward2__'));
            $this->error('操作失败');
        }

        //数据
        if($id){
            $info = Db::name('wh_material')->where(['id'=>$id])->find();
            $info['is_order_color'] = $info['order_ids'];

            $type_pid = $info['type_pid'];

            if(!empty($info['order_ids']) && in_array($type_pid,ColorModel::$type_pid_arr)){
                if(!empty($order_ids))$info['order_ids'] = $order_ids;
                $info['order_color_ids'] = '';
                $info['lists'] = Db::name('mill_order')->where([['id','in',$info['order_ids']]])->select();
                foreach ($info['lists'] as &$v){
                    //总面积
                    $v['row_area'] = 0;
                    $where = [
                        ['g.order_id','=',$v['id']],
                        ['g.material_id','=',$info['id']],
                    ];
                    $v['lists'] = Db::name('wh_material_goods')
                        ->alias('g')
                        ->field('g.*,o.archives_sn,o.engineering,s.title as supplier,st.title as type_name,ct.title as color_type_name')
                        ->leftJoin('mill_order o','g.order_id=o.id')
                        //->leftJoin('wh_order_color c','g.color_id=c.id')
                        ->leftJoin('wh_supplier s','g.supplier_id=s.id')
                        ->leftJoin('wh_stock_type st','g.type_id=st.id')
                        ->leftJoin('wh_supplier_color_type ct','g.color_type_id=ct.id')
                        ->where($where)
                        ->order('g.id asc')
                        ->select();
                    foreach ($v['lists'] as &$vv){
                        //供应商
                        $v['supplier'] = $vv['supplier'];
                        $info['supplier_id'] = $vv['supplier_id'];
                        //总面积
                        $v['row_area'] += $vv['row_area'];
                        $info['row_area'] += $vv['row_area'];
                        //采购量
                        $info['number'] += $vv['number'];
                        //订单颜色ID
                        $info['order_color_ids'] .= ",{$vv['order_color_id']}";
                        //获取库存
                        $vv['sum_number'] = StockModel::getSumNumber($vv);
                    };
                }
            }
            else {
                $info['lists'] = Db::name('wh_material_goods')->where([['material_id','=',$info['id']]])->select();
                foreach ($info['lists'] as &$v){
                    //总面积
                    if(empty($v['row_area']))$v['row_area'] = 0;
                    //获取库存
                    $v['sum_number'] = StockModel::getSumNumber($v);
                    /*if($v['type_pid'] == 5){
                        $v['row_area2'] = $v['row_area'];
                        //理论重量
                        $v['kg'] = $v['long']*$v['high']*$v['row_area'];
                        //实际重量
                        $v['kg2'] = $v['long']*$v['high']*$v['row_area'];
                        //材质 order_id="+order_id+"&thickness="+
                        $type_text = floatval(Db::name('wh_stock_type')->where(['id'=>$v['type_id']])->value('title'));
                        $v['model_list'] = $this->getOrderArchives(['order_id'=>$v['order_id'],'thickness'=>$type_text,'re_type'=>1]);
                        foreach ($v['model_list'] as &$vv){
                            $vv['id'] = $vv['model'];
                            $vv['title'] = $vv['model'];
                            $vv['data_html'] = "data-row_area='{$vv['row_area']}'";
                        }
                    }*/

                }
            }

        }
        elseif ($ainp_id){
            $info = Db::name('wh_material_ainp')->where(['id'=>$ainp_id])->find();
            $info['id'] = '';
            $info['uid'] = UID;//申请人
            $info['material_sn'] = MaterialModel::getMaterialSn();//采购单编号
            $info['create_time'] = time();//创建日期
            $info['address_time'] = time();//到货时间
            $info['urgent_status'] = '';//加急状态

            $type_pid = $info['type_pid'];

            $info['lists'] = json_decode($info['goods'],true);
            $new_list = [];
            foreach ($info['lists'] as &$v){
                $v['stock_sn'] = '';
                $v['lot_sn'] = '';
                if(empty($v['num']))$v['num'] = 1;
                //获取库存
                $v['sum_number'] = StockModel::getSumNumber($v);

                for($i=$v['num'];$i>0;$i--){
                    $v['num'] = 1;
                    $new_list[] = $v;
                }

            }
            $info['lists'] = $new_list;
        }
        else{

            $info['id'] = '';
            $info['uid'] = UID;//申请人
            $info['material_sn'] = MaterialModel::getMaterialSn();//采购单编号
            $info['order_ids'] = $order_ids;//订单ID
            $info['order_color_ids'] = '';//订单颜色ID
            $info['type_pid'] = $type_pid;//采购类别 喷涂，转印等
            $info['type_id'] = 1;//物料类型 暂时写死
            $info['row_area'] = 0;//总面积
            $info['number'] = 0;//采购量
            $info['note'] = '';//备注
            $info['create_time'] = time();//创建日期
            $info['address_time'] = time();//到货时间
            $info['address_time'] = '';//到货时间
            $info['urgent_status'] = '';//加急状态
            $info['is_order_color'] = $is_order_color;//是否按确认颜色的工程来创建采购单 0:不按工程 1:按工程

            if($is_order_color && in_array($type_pid,ColorModel::$type_pid_arr)){
                $info['lists'] = Db::name('mill_order')->where([['id','in',$order_ids]])->select();

                foreach ($info['lists'] as &$v){
                    //总面积
                    $v['row_area'] = 0;
                    //颜色
                    $where = [['c.order_id','=',$v['id']],['c.type_pid','=',$type_pid],['c.id','in',$order_color_ids]];
                    if(!empty($not_order_color_ids))$where[] = ['c.id','not in',$not_order_color_ids];
                    //$where[] = ['c.status','>=',1];
                    $v['lists'] = Db::name('wh_order_color')
                        ->alias('c')
                        ->field('c.*,c.color as material_name,sc.number as sum_number,o.archives_sn,o.engineering,s.title as supplier,st.title as type_name,ct.title as color_type_name')
                        ->leftJoin('mill_order o','c.order_id=o.id')
                        ->leftJoin('wh_stock sc','c.stock_id=sc.id')
                        ->leftJoin('wh_supplier s','c.supplier_id=s.id')
                        ->leftJoin('wh_stock_type st','c.type_id=st.id')
                        ->leftJoin('wh_supplier_color_type ct','c.color_type_id=ct.id')
                        ->where($where)
                        ->order('c.id asc')
                        ->select();
                    $v['supplier'] = '';
                    foreach ($v['lists'] as &$vv){
                        //供应商
                        $v['supplier'] = $vv['supplier'];
                        $info['supplier_id'] = $vv['supplier_id'];
                        //总面积
                        $v['row_area'] += $vv['row_area'];
                        $info['row_area'] += $vv['row_area'];
                        //采购量
                        $info['number'] += $vv['number'];
                        //订单颜色ID
                        $info['order_color_ids'] .= ",{$vv['id']}";
                        //获取库存
                        //$vv['sum_number'] = ColorModel::getSupplierColorNum($vv['color_id']);
                        //获取库存编号
                        //$vv['stock_sn'] = StockModel::getStockSn($vv,false);
                        //采购单ID
                        $vv['material_id'] = '';
                        $vv['type_pid'] = $info['type_pid'];
                        $vv['order_color_id'] = $vv['id'];
                        $vv['material_name'] = $vv['color'];
                        $vv['model'] = $vv['supplier_color'];
                        $vv['id'] = '';
                        $vv['price'] = 0;
                        $vv['sum_price'] = 0;
                    };
                }
            }
            else{
                $info['lists'] = [[
                    'id'                =>  '',
                    'stock_id'          =>  '',
                    'stock_sn'          =>  '',
                    'material_id'       =>  '',
                    'order_id'          =>  '',
                    'archives_sn'       =>  '',
                    'supplier_id'       =>  '',
                    'type_pid'          =>  $type_pid,
                    'type_id'           =>  '',
                    'type_id2'          =>  '',
                    'type_id3'          =>  '',
                    'material_name'     =>  '',
                    'sum_number'        =>  '',
                    'number'            =>  '',
                    'sum_num'           =>  '',
                    'num'               =>  '',
                    'price'             =>  '',
                    'sum_price'         =>  '',
                    'model'             =>  '',
                    //'model_list'        =>  [],
                    'long'              =>  '',
                    'high'              =>  '',
                    'quality'           =>  '',
                    'lot_sn'            =>  '',
                    'row_area'          =>  '',
                    'row_area2'         =>  '',
                    'kg'                =>  '',
                    'kg2'               =>  '',
                    'supplier_color'    =>  '',
                    'color_type_id'     =>  '',
                    'order_color_id'    =>  '',
                    'heat'              =>  0,
                    'color_sn'          =>  '',
                    'supplier_name'     =>  '',
                    'type_pname'        =>  '',
                    'type_name'         =>  '',
                    'color_type_name'   =>  '',
                ]];
            }
        }
        $info['stock_type'] = StockTypeModel::getGroup($type_pid);
        //$info['stock_type2'] = StockTypeModel::getGroup(0,false,[['pid','in',implode(',',array_keys($info['stock_type']))]]);
        //$info['stock_type3'] = StockTypeModel::getGroup(0,false,[['pid','in',implode(',',array_keys($info['stock_type2']))]]);
        $info['supplier'] = SupplierModel::getGroup(0,$type_pid);
        $info['quality'] = ColorModel::getQuality($type_pid);
        $info['color_type'] = ColorModel::getColorType();
        $info['heat'] = MaterialModel::$heat;
        $info['order'] = OrderModel::getList("CONCAT(engineering,' ',archives_sn,' ',batch)",['status'=>1]);
        $info['model_list'] = [];
        $info['order_color_ids'] = trim($info['order_color_ids'],',');
        $info['nickname'] = get_nickname($info['uid']);
        $info['type_name'] = StockTypeModel::getTypeName($type_pid);

        //物料类型
        $tab_css = '';
        $list_tab = [];
        $type_list = StockTypeModel::getGroup(0,true);
        foreach ($type_list as $tlk=>$tlv){

            if($tlk == 8){
                unset($type_list[$tlk]);
                continue;
            }
            if(!$is_order_color && !in_array($tlk,ColorModel::$type_pid_arr)){
                unset($type_list[$tlk]);
                continue;
            }

            $get['id'] = $id;
            $get['is_order_color'] = $is_order_color;
            $get['type_pid'] = $tlk;
            $url_parm = '';
            //if(!empty($order_ids))$url_parm .= "?order_ids={$order_ids}";
            $list_tab[$tlk] = ['title' => $tlv['title'],'icon' => $tlv['icon'], 'url' => url('add', $get).$url_parm];

            $tab_css .= StockTypeModel::cssNavColor($tlk,$tlv['color']);

            if($id && $type_pid != $tlk)unset($list_tab[$tlk]);
        }
        $list_tab = StockTypeModel::getTabNav('add');

        $fromData = MaterialModel::getTabFrom($type_pid,$info,$print);
        $fromItems = $fromData['from'];

        $method = ['method'=>'post','submit'=>'提交','isAjax'=>'ajax-post'];

        if(empty($info['id']) && empty($info['order_ids']) && $is_order_color && in_array($type_pid,ColorModel::$type_pid_arr))$method = ['method'=>'get','submit'=>'下一步','isAjax'=>'select-get'];

        if(empty($is_add))$method['isAjax'] = 'hidden';

        //CSS
        $css = $fromData['css'];
        $css .= "<style>
                {$tab_css}
                #table-order > thead > tr > th:has(.new-table-head){padding: unset;border: hidden;}
                th:has(.new-table-head-flex-2){background-color: rgba(0,0,0,0);font-weight: bold;border-bottom: 3px solid #fff;}
                th,td:has(.new-table-head-2){background-color: #CCE3FE;font-weight: bold;}
                .new-table-head span .select2{width: auto;height: 30px;margin-left: -10px;}
                .new-table-head span .selection{margin: unset}
                .form-group .select2-container .select2-selection--single {height: 26px;}
                .form-group .select2-container--default .select2-selection--single .select2-selection__rendered {line-height: 26px;}
                
                #table-selectorder .new-table-head{border-right: 1px #fff solid;}
                #table-selectorder .new-table-head span{color: #fff}
                
                
                .btn-bottom-float {position: fixed;left: 0px;bottom: 10px;}
                .td-bg-color {background-color: #f9fafc}
                
                .dch-ul {width: 100%;padding: 0;margin: 0;}
                .dch-li {list-style-type: none;}
                .dch-bottom {border-bottom: 1px solid #f0f0f0;}
                
                .goods-submit {background-color: unset;color: #A2EF4D;float: right;}
                .layui-table th, .layui-border-box th {background-color: unset;}
                
            </style>";

        //JS
        $js = $fromData['js'];
        $js .= '<script type="text/javascript">
                

                //监听选择框
                layui.form.on(\'select(info[urgent_status])\',function(data){
                    console.log("选中的值: " + data.value); // 获取到选中的值
                    console.log("选中的文本: " + data.elem[data.elem.selectedIndex].text); // 获取到选中的文本
                    console.log("事件对象: " + data.elem); // 获取到触发事件的元素对象
                    
                });
                
                
                $("body").on("keyup","input[name=\'info[note]\']",function(){
                    $("select[name=\'info[urgent_status]\']").val("");//设置选中的值  TypeID为HTML标签ID
                    console.log("设置选中的值: " + $("select[name=\'info[urgent_status]\']").val()); // 获取到选中的值
                    //刷新表单
                    layui.form.render();
                });
                
                
                //喷涂取消定量
                function order_color_del(obj) {
                    var order_id = $(obj).data("order-id");
                    var order_color_id = $(obj).data("order-color-id");
                    var count_order_id = $("a[data-order-id="+order_id+"]").length;
                    
                    var href_arr = window.location.href.split("?");//分隔URL和参数
                    var href = href_arr[0];
                    var href_p = getUrlParms(href_arr[1]);//将URL参数数组化
                    
                    //取消选购
                    var order_color_ids = href_p.order_color_ids.split(",");
                    //console.log(order_color_id);
                    //console.log(href_p.order_color_ids);
                    while ($.inArray(""+order_color_id, order_color_ids) !== -1) {
                        var index =$.inArray(""+order_color_id, order_color_ids);
                        order_color_ids.splice(index, 1);
                    }
                    href_p.order_color_ids = order_color_ids.join(",");
                    //如果取消选购的定色，该工程只有一个，则同时删除工程
                    var order_ids = href_p.order_ids.split(",");
                    if(count_order_id <= 1){
                        while ($.inArray(""+order_id, order_ids) !== -1) {
                            var index =$.inArray(""+order_id, order_ids);
                            order_ids.splice(index, 1);
                        }
                    //console.log(order_id);
                    //console.log(href_p.order_ids);
                    }
                    href_p.order_ids = order_ids.join(",");
                    //console.log(href_p);
                    
                    var href_p_2 = "";
                    $.each(href_p,function(i,j){
                        if(href_p_2)href_p_2 += "&";
                        href_p_2 += i+"="+j;
                    });
                    
                    //重组URL参数，并跳转
                    window.location.href = href+"?"+href_p_2;
                }
                function getUrlParms(parms){
                    var args=new Object();
                    var query=parms;//获取查询串
                    var pairs=query.split("&");//在逗号处断开
                    for(var i=0;i<pairs.length;i++)
                    {  
                        var pos=pairs[i].indexOf(\'=\');//查找name=value
                            if(pos==-1)   continue;//如果没有找到就跳过
                            var argname=pairs[i].substring(0,pos);//提取name
                            var value=pairs[i].substring(pos+1);//提取value
                            args[argname]=unescape(value);//存为属性
                    }
                    return args;
                }
                
                
                //禁用输入框
                var type_pid = '.$type_pid.';
                $("input[name=\'goods[sum_number][]\']").attr("placeholder","自动获取库存");
                $("input[name=\'goods[sum_number][]\']").attr("disabled","disabled");
                
                //删除
                function goods_del(obj) {
                    var length = $(".goods_del").parent("td").parent("tr").length;
                    
                    if(length == 1){
                        return false;
                    }
                    $(obj).parent().parent().remove();
                }
                //新增
                function goods_add(obj) {
                    var add = $(".goods").parent().parent().html();
                    add = "<tr class=\'hidden\'>"+add+"</tr>";
                    $(add).insertAfter($(".goods").parent("td").parent("tr:last"));
                    $(".goods").parent("td").parent("tr:last").find("span.select2").remove();
                    $(".goods").parent("td").parent("tr:last").removeClass("hidden");
                    $(".goods").parent("td").parent("tr:last").find("input[name=\'goods[id][]\']").val("");
                    
                    App.initHelpers(["select2"]);
                }
                //查询库存
                function sum_number_show(obj) {
                    var tr_obj = $(obj).parents("tr");
                    var num_obj = $(tr_obj).find("input[name=\'goods[sum_number][]\']");
                    var type_pid = tr_obj.find("input[name=\'goods[type_pid][]\']").val();
                    var type_id = tr_obj.find("select[name=\'goods[type_id][]\']").val();
                    var supplier_id = tr_obj.find("select[name=\'goods[supplier_id][]\']").val();
                    var model = tr_obj.find("input[name=\'goods[model][]\']").val();
                    //查询库存
                    $.ajax({
                        url: "'.url("getSumNumber").'?type_id="+type_id+"&type_pid="+type_pid+"&supplier_id="+supplier_id+"&model="+model,
                        type: "GET"
                    }).done(function(data) {
                        data = $.parseJSON(data);
                        
                        num_obj.val(data.sum_number);
                    });
                }
                //获取材质
                //物料类别,订单选择事件
                $("body").on("change","select[name=\'goods[order_id][]\'],select[name=\'goods[type_id][]\']",function(){
                    var tr_obj = $(this).parents("tr");
                    var type_pid = tr_obj.find("input[name=\'goods[type_pid][]\']").val();
                    var order_id = tr_obj.find("select[name=\'goods[order_id][]\']").val();
                    var type_id = tr_obj.find("select[name=\'goods[type_id][]\']").val();
                    var type_obj = tr_obj.find("select[name=\'goods[type_id][]\']").find("option[value=\'"+type_id+"\']");
                    var type_text = parseFloat(type_obj.html());
                    
                });
                //计算总量
                //材质点击事件
                $("body").on("change","select[name=\'goods[model][]\']",function(){
                    var tr_obj = $(this).parents("tr");
                    var type_pid = tr_obj.find("input[name=\'goods[type_pid][]\']").val();
                    
                });
                //长宽点击事件
                $("body").on("keyup","input[name=\'goods[long][]\'],input[name=\'goods[high][]\'],select[name=\'goods[model][]\']",function(){
                    var tr_obj = $(this).parents("tr");
                    var type_pid = tr_obj.find("input[name=\'goods[type_pid][]\']").val();
                    var long = tr_obj.find("input[name=\'goods[long][]\']").val();
                    var high = tr_obj.find("input[name=\'goods[high][]\']").val();
                    var model = tr_obj.find("select[name=\'goods[model][]\']").val();
                    var row_area = tr_obj.find("select[name=\'goods[model][]\']").find("option[value=\'"+model+"\']").data("row_area");
                    
                    long = parseFloat(long) || "";
                    high = parseFloat(high) || "";
                    row_area = parseFloat(row_area) || "";
                    
                });
                //长宽点击事件
                $("body").on("keyup","input[name=\'goods[long][]\'],input[name=\'goods[high][]\'],select[name=\'goods[model][]\']",function(){
                    var tr_obj = $(this).parents("tr");
                    var type_pid = tr_obj.find("input[name=\'goods[type_pid][]\']").val();
                    var long = tr_obj.find("input[name=\'goods[long][]\']").val();
                    var high = tr_obj.find("input[name=\'goods[high][]\']").val();
                    var model = tr_obj.find("select[name=\'goods[model][]\']").val();
                    var row_area = tr_obj.find("select[name=\'goods[model][]\']").find("option[value=\'"+model+"\']").data("row_area");
                    
                    long = parseFloat(long) || "";
                    high = parseFloat(high) || "";
                    row_area = parseFloat(row_area) || "";
                    
                });
                
                //喷涂新增工程点击事件
                $("body").on("change",".order_add",function(){
                    var val = $(this).val();
                    var option = $(this).find("option[value=\'"+val+"\']");
                    
                    $(".order_add_engineering").html(option.data("engineering"));
                    $(".order_add_row_area").html(option.data("row-area"));
                    $(".order_add_sales").html(option.data("sales"));
                    $(".order_add_back").html(option.data("back"));
                    
                    $(".order-add-a").data("order-id",val);
                    
                });
                
                //喷涂
                var order_ids = "'.$order_ids.'";//已选择的订单
                var not_order_color_ids = "'.$not_order_color_ids.'";//已取消的定量
                //喷涂新增工程
                function order_add(obj) {
                    var id = $(obj).data("id");
                    var order_id = $(obj).data("order-id");
                    //var order_ids = $(obj).data("order-ids");
                    var type_pid = $(obj).data("type-pid");
                    
                    if(!order_id)Dolphin.notify("请选择工程", "danger");
                    else{
                        
                        var href = window.location.href;
                        var href_p = new RegExp("order_ids="+order_ids,"g");
                        
                        if(order_ids)order_ids = ","+order_ids+",";
                        //去重
                        var order_ids_test = order_ids.indexOf(","+order_id+",");
                        
                        if(order_ids_test < 0)order_ids += order_id;
                        //去掉首尾逗号
                        order_ids = order_ids.replace(/(^,)|(,$)/g,"");
                        //替换链接地址上的旧order_ids
                        href = href.replace(href_p, "order_ids="+order_ids);
                        if(href.indexOf("order_id")<0)href += "?order_ids="+order_ids;
                        if(href.indexOf("order_id")>0 && not_order_color_ids)href += "&not_order_color_ids="+not_order_color_ids;
                        window.location.href = href;
                    }
                }
                //喷涂删除工程
                function order_del(obj) {
                    var order_id = $(obj).data("order-id");
                    //var order_ids = $(obj).data("order-ids");
                    var href_p = new RegExp("order_ids="+order_ids,"g");
                    var length = $(".goods_del").parent("td").parent("tr").length;
                    
                    if(length == 1){
                        //return false;
                        //Dolphin.notify("请选择工程", "danger");
                    }
                    
                    order_ids = ","+order_ids+",";
                    order_ids = order_ids.replace(","+order_id+",",",");
                    //去掉首尾逗号
                    order_ids = order_ids.replace(/(^,)|(,$)/g,"");
                    
                    var href = window.location.href;
                    
                    //替换链接地址上的旧order_ids
                    if(order_ids){
                        href = href.replace(href_p, "order_ids="+order_ids);
                        
                        if(href.indexOf("order_id")<0 && order_ids)href += "?order_ids="+order_ids;
                        if(not_order_color_ids)href += "&not_order_color_ids="+not_order_color_ids;
                    }
                    else{
                        href = href.substring(0,href.indexOf("?"));
                    }
                    if (href.substr(-1) === "?")href = href.replace("?","");
                    if (href.substr(-1) === "&")href = href.replace("&","");
                    window.location.href = href;
                }
                
                //厂家色号，子窗口赋值
                function setSupplierColor(rel){
                    this.rel=rel;
                    //赋值处理
                    supplier_color_show(rel);
                }
                //厂家色号，子窗口获取值
                function getSupplierColor(){
                    return rel;
                }
                //打开厂家色号列表
                function supplier_color_list(obj) {
                    var color_obj = $(obj).prev("input[name=\'goods[supplier_color][]\']");
                    var type_pid = $(obj).siblings("input[name=\'goods[type_pid][]\']").val();
                    //厂家色号
                    var color = color_obj.val();
                    //地址
                    //var href = $(obj).data("href")+"?_s=c.title="+color+"&_o=c.title=like";
                    var href = $(obj).data("href")+"?_s=c.model="+color+"|c.type_pid="+type_pid+"&_o=c.model=like|c.type_pid=eq";
                    //当前点击事件的索引
                    var index = $("input[name=\'goods[supplier_color][]\']").index(color_obj);
                    href = href.replace(/__parent_i__/,index);
                    $(obj).attr("href",href);
                }
                //查询厂家色号对应供应商
                function supplier_color_show(rel) {
                    var obj = $("input[name=\'goods[supplier_color][]\']").eq(rel._parent_i);
                    
                    //查询厂家色号对应供应商
                    $.ajax({
                        url: \''.url("getSupplier").'?id=\'+rel.id,
                        type: \'GET\'
                    }).done(function(data) {
                        data = $.parseJSON(data);
                        var supplier = data.supplier;
                        
                        if(!data.supplier)Dolphin.notify("查询无该色号，请填写后续信息！", "danger");
                        else{
                            //Dolphin.notify("已有该厂家色号，请选择供应商！", "success");
                            
                            //自动填充
                            obj.val(supplier.model);
                            $(obj).siblings("input[name=\'goods[stock_sn][]\']").val(supplier.stock_sn);
                            
                            $(obj).siblings("input[name=\'goods[model][]\']").val(supplier.model);
                            $(obj).siblings("input[name=\'goods[material_name][]\']").val(supplier.title);
                            $(obj).parent().parent().parent().find(".material_name").text(supplier.title);
                            
                            $(obj).siblings("input[name=\'goods[supplier_id][]\']").val(supplier.supplier_id);
                            $(obj).parent().parent().parent().find(".supplier_title").text(supplier.supplier_title);
                            
                            $(obj).siblings("input[name=\'goods[type_pid][]\']").val(supplier.type_pid);
                            $(obj).parent().parent().parent().find(".type_ptitle").text(supplier.type_ptitle);
                            
                            $(obj).siblings("input[name=\'goods[type_id][]\']").val(supplier.type_id);
                            $(obj).parent().parent().parent().find(".type_title").text(supplier.type_title);
                            
                            $(obj).siblings("input[name=\'goods[type_id2][]\']").val(supplier.type_id2);
                            $(obj).parent().parent().parent().find(".type_title2").text(supplier.type_title2);
                            
                            $(obj).siblings("input[name=\'goods[type_id3][]\']").val(supplier.type_id3);
                            $(obj).parent().parent().parent().find(".type_title3").text(supplier.type_title3);
                            
                            $(obj).siblings("input[name=\'goods[heat][]\']").val(supplier.heat);
                            $(obj).parent().parent().parent().find(".heat_title").text(supplier.heat_title);
                            
                            $(obj).siblings("input[name=\'goods[color_type_id][]\']").val(supplier.color_type_id);
                            $(obj).parent().parent().parent().find(".color_type_title").text(supplier.color_type_title);
                            
                            $(obj).siblings("input[name=\'goods[color_sn][]\']").val(supplier.color_sn);
                            $(obj).parent().parent().parent().find(".color_sn").text(supplier.color_sn);
                            
                            $(obj).parent().parent().parent().find(".sum_number").text(supplier.number);
                            
                        }
                    });
                            
                }
            </script>';

        $title = '新建采购单';
        //if($id)$title = '采购单详情';
        return ZBuilder::make('form')
            ->setPageTitle($title) // 页面标题
            ->setTabNav($list_tab,$type_pid)
            //->setExtraHtml($this->_top_html,'block_top')
            ->addHidden('uid')
            ->addHidden('order_ids')
            ->addHidden('order_color_ids')
            ->addHidden('supplier_id')
            ->addHidden('type_pid')
            ->addHidden('type_id')
            ->addHidden('row_area')
            ->addHidden('number')
            ->addHidden('status')
            ->addSelect('','仅加载select插件用','', $info['supplier'],'','','hidden')
            ->addDate('','仅加载date插件用','', '','','','hidden')
            ->addFormItems($fromItems)
            ->setFormData($info)
            ->setExtraJs($js)
            ->setExtraCss($css)
            //->hideBtn(['submit', 'back'])
            ->method($method['method'])
            //->addBtn('<button type="submit" class="btn btn-radius btn-lg btn-minlg btn-primary '.$method['isAjax'].'" target-form="form-builder" >'.$method['submit'].'</button>')
            //->addBtn('<button type="button" class="btn btn-radius btn-lg btn-minlg bg-info-light" onclick="window.location.href=\''.cookie('__forward__').'\';return false;">返回</button>')
            ->layout(['note'=>12])
            ->fetch();

    }

    //不按工程新建油漆类采购单
    public function add2($id=null)
    {
        return $this->add();
    }

    //详情
    public function show(){
        return $this->add(false);
    }

    //获取库存
    public function getSumNumber(){

        $input = input();

        $sum_number = StockModel::getSumNumber($input);

        echo json_encode(['sum_number'=>$sum_number],JSON_UNESCAPED_UNICODE);exit;
    }

    //获取面积表信息
    public function getOrderArchives($input = [],$group = ''){

        $re_type = '';
        if(empty($input))$input = input();
        if(!empty($input['group']))$group = $input['group'];
        if(!empty($input['re_type']))$re_type = $input['re_type'];

        $where = [['order_id','=',$input['order_id']]];
        if($input['thickness'])$where[] = ['thickness','=',$input['thickness']];

        $field = 'id,model,SUM(row_area) as row_area';
        $list = ArchivesModel::getList($input['order_id'],$field,'sort asc',$group,[],$where);
        if(empty($list[0]['id']))$list = [];

        if($re_type == 1)return $list;
        echo json_encode(['list'=>$list],JSON_UNESCAPED_UNICODE);exit;
    }

    /**
     * 选择批次
     * @return mixed
     */
    public function selectOrder()
    {

        $type_pid = $this->_type_id;
        // 获取查询条件
        $map = $this->getMap();
        //$map[] = ['m.type_pid','=',$type_pid];

        $fromItems = MaterialModel::fromSelect($type_pid,true,$map);

        $html = '';

        $commplextable = new Builder();
        $data = $commplextable->item('','',$fromItems['data']);

        foreach ($data['data'] as $v){
            $html .= '<tr>';
            foreach ($v as $vo){

                $style = 'vertical-align: middle; ';
                if(is_array($vo["value"]))$style .= 'padding:0;';
                $rowspan = '';
                if(!empty($vo['rowspan']))$rowspan = "rowspan='{$vo['rowspan']}'";
                $colspan = '';
                if(!empty($vo['colspan']))$colspan = "colspan='{$vo['colspan']}'";

                $html .= "<td style='{$style}' {$rowspan} {$colspan}>{$vo['value']}</td>";
            }
            $html .= '</tr>';
        }

        exit($html);
    }

    //取消颜色定量
    public function rationSubs(){
        $action = new Color();

        return $action->rationSubs();
    }

    /**
     * 删除
     * @return mixed
     */
    public function delete($record = [])
    {

        if ($this->request->isPost()) {
            $data = $this->request->post();

            $ids = $data['ids'];

            if(empty($ids))$this->error('请选择采购单');

            foreach ($ids as $id){
                $info = Db::name('wh_material')->where(['id'=>$id])->find();

                //获取库存编号，处理库存数据
                $stock_sns = Db::name('wh_material_goods')->where(['material_id'=>$id])->column('stock_sn');
                if(!empty($stock_sns)){
                    foreach ($stock_sns as $stock_sn){
                        //清空库存批号
                        StockModel::upStockNumber(3,$stock_sn);
                    }
                }

                Db::name('wh_material')->where(['id'=>$id])->delete();
                Db::name('wh_material_goods')->where(['material_id'=>$id])->delete();
                if(!empty($info['order_color_ids']))Db::name('wh_order_color')->where([['id','in',$info['order_color_ids']]])->update(['status'=>1]);
            }

            $this->success('操作成功');
        }

        $this->error('请选择采购单');

    }

    /**
     * 我发起的采购单
     */
    public function myList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        cookie('__forward2__', $_SERVER['REQUEST_URI']);

        $type_pid = $this->_type_id;

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['m.type_pid','=',$type_pid];

        $list_tab = StockTypeModel::getTabNav('myList');

        //------------------------------ 采购部权限 ----------------------------------
        //获取部门ID，采购部的只看自己的采购单
        //采购部ID：13,15
        $user_group = [13,15];
        //采购部的只看自己的采购单
        //if(in_array(session('user_auth.group'),$user_group))$map[] = ['m.uid','=',UID];
        //只能查看角色权限内的物料类型采购单
        //$type_pids = Db::name('admin_role')->where(['id'=>session('user_auth.role')])->value('stock_type_ids');
        //if(!empty($type_pids))$map[] = ['m.type_pid','in',$type_pids];

        // 数据列表
        $data_list = Db::name('wh_material')
            ->alias('m')
            ->field('m.*,s.title_abb as supplier_name,u.nickname,uu.nickname as status_nickname,t.title as type_name')
            ->leftJoin('wh_supplier s','m.supplier_id=s.id')
            ->leftJoin('admin_user u','m.uid=u.id')
            ->leftJoin('admin_user uu','m.status_verify_uid=uu.id')
            ->leftJoin('wh_stock_type t','m.type_pid=t.id')
            ->where($map)
            ->order('m.id desc')
            ->paginate()
            ->each(function ($v){

                //采购单信息
                $html = '
						<div class="layui-col-md8">
							<span class="text-black">采购单编码：'.$v['material_sn'].' </span>
							<a class="table-btn text-white" href="javascript:void(0);" data-toggle="tooltip" title="删除"><i class="layui-icon layui-icon-delete"></i></a>
							<a class="table-btn text-white" href="javascript:void(0);" data-toggle="tooltip" data-original-title="编辑"><i class="layui-icon layui-icon-edit"></i></a>
							<a class="table-btn text-white" href="javascript:void(0);" data-toggle="tooltip" data-original-title="打印"><i class="layui-icon layui-icon-print"></i></a>
							<a class="table-btn text-success" href="javascript:void(0);" data-toggle="tooltip" data-original-title="已审核"><i class="layui-icon layui-icon-vercode"></i></a>
							<span>申请人：吴晶晶</span>
							<span>采购人：吴晶晶</span>
							<span>审批人：吴晶晶</span>
						</div>
						<div class="layui-col-md3">
							'.MaterialModel::status_bar_tag($v['status']).'
						</div>
						<div class="layui-col-md1">
							<span>'.MaterialModel::$status[$v['status']].'</span>
						</div>
						
						
						<div class="layui-col-md12 new-table-head-flex text-black">
                            <span>采购形式：关联采购</span>
                            <span>采购内容：'.$v['type_name'].'</span>
                            <span>采购数量：'.$v['number'].'(kg)</span>
                            <span>订单状态：'.MaterialModel::$urgent_status[$v['urgent_status']].'</span>
                            <span>采购日期：'.date('Y-m-d',$v['create_time']).'</span>
                            <span>预估到货：'.date('Y-m-d',$v['address_time']).'<a class="btn btn-primary new-table-body-show" style="float: right;" data-id="'.$v['id'].'">点击展开</a></span>
                            
						</div>
					';

                $v['title'] = $html;

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('我发起的采购单') // 页面标题
            ->setTableName('wh_material') // 设置表名
            ->setTabNav($list_tab,$type_pid)
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'm.material_sn', '采购单', 'like'],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['select:2', 'm.supplier_id', '供应商', 'eq','',SupplierModel::getGroup()],
                ['text:2', 'g.supplier_color', '颜色编号', 'like'],
                //['select:1', 'm.type_pid', '采购类型', 'eq','',StockTypeModel::getGroup()],
                ['daterange:2', 'm.create_time', '采购日期'],
                ['select:1', 'm.status', '采购状态', 'eq','',MaterialModel::$status],
            ])
            ->addTrClass('hidden-remove','title','<>','')
            ->hideColumn('title','remove')
            ->addColumns([ // 批量添加列
                ['material_sn', '采购单号'],
                ['create_time', '建单日期','date'],
                ['urgent_status', '需求','','',MaterialModel::$urgent_status],
                ['supplier_id', '供应商','','',SupplierModel::getGroup()],
                ['status', '采购单状态','','',MaterialModel::$status],
                ['nickname', '发起采购'],
                ['status_nickname', '审核人'],
                ['type_pid', '采购内容','','',StockTypeModel::getGroup()],
                ['note222', '采购形式'],
                ['number', '采购数量'],
                ['price', '采购金额'],
                ['engineering', '工程名称'],
                ['engineering2222', '采购内容'],
                ['engineering333', '打印状态'],
                ['note', '备注'],
                ['right_button', '操作', 'btn'],
            ])
            //->addTopButton('selectOrder',['title' => '新增采购单','href' => url('selectOrder'),'icon'=>'','class'=>'btn btn-primary'],['area' => ['780px', '40%'], 'title' => ['新增采购单', 'font-size:24px;text-align: center;']])
            //->addTopButton('add2',['title' => '直接新增采购单','href' => url('add',['is_order_color'=>0,'type_pid'=>1]),'icon'=>'','class'=>'btn btn-primary'])
            //->addTopButton('add',['title' => '新增采购单','href' => url('add',['type_pid'=>1]),'icon'=>'','class'=>'btn btn-primary'])
            //->addTopButton('delete',['title' => '删除','icon'=>'','class'=>'btn bg-info-light ajax-post confirm'])
            ->addRightButton('delete',['title' => '删除', 'href' => url('delete', [ 'id' => '__id__']),'icon'=>'','class'=>'btn bg-info-light ajax-post confirm'])
            ->addRightButton('add', ['title' => '修改', 'href' => url('add', [ 'id' => '__id__']), 'icon' => '','class'=>'btn bg-info-light'])
            //->addRightButton('show', ['title' => '查看', 'href' => url('add', [ 'id' => '__id__']), 'icon' => ''])
            //->addRightButton('showPrint',['title' => '导出','href' => url('showPrint',['id'=>'__id__','print'=>'2']),'class'=>'btn bg-info-light disable-dch','icon'=>'','target'=>'_blank'])
            //->addRightButton('showPrint',['title' => '打印','href' => url('showPrint',['id'=>'__id__','print'=>'1']),'class'=>'btn bg-info-light disable-dch','icon'=>'','target'=>'_blank'])
            //->addRightButton('codePrint',['title' => '打印条码','href' => url('wh/stock/codePrint',['material_id' => '__id__','page'=>1]),'class'=>'btn bg-info-light disable-dch','icon'=>''],['area' => ['780px', '90%'], 'title' => ['正在打印中...', 'font-size:24px;text-align: center;']])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'title'  => 20,
                'title2'  => 20,
            ])
            ->fetch(); // 渲染模板
    }
    public function myList_old()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        cookie('__forward2__', $_SERVER['REQUEST_URI']);

        $type_pid = $this->_type_id;

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['m.type_pid','=',$type_pid];

        //------------------------------ 采购部权限 ----------------------------------
        //获取部门ID，采购部的只看自己的采购单
        //采购部ID：13,15
        $user_group = [13,15];
        //采购部的只看自己的采购单
        //if(in_array(session('user_auth.group'),$user_group))$map[] = ['m.uid','=',UID];
        //只能查看角色权限内的物料类型采购单
        //$type_pids = Db::name('admin_role')->where(['id'=>session('user_auth.role')])->value('stock_type_ids');
        //if(!empty($type_pids))$map[] = ['m.type_pid','in',$type_pids];

        // 数据列表
        $data_list = Db::name('wh_material')
            ->alias('m')
            ->field('m.*,s.title_abb as supplier_name,u.nickname,t.title as type_name')
            ->leftJoin('wh_supplier s','m.supplier_id=s.id')
            ->leftJoin('admin_user u','m.uid=u.id')
            ->leftJoin('wh_stock_type t','m.type_pid=t.id')
            ->where($map)
            ->order('m.id desc')
            ->paginate()
            ->each(function ($v){

                //采购单信息
                $html = '
						<div class="layui-col-md8">
							<span class="text-black">采购单编码：'.$v['material_sn'].' </span>
							<a class="table-btn text-white" href="javascript:void(0);" data-toggle="tooltip" title="删除"><i class="layui-icon layui-icon-delete"></i></a>
							<a class="table-btn text-white" href="javascript:void(0);" data-toggle="tooltip" data-original-title="编辑"><i class="layui-icon layui-icon-edit"></i></a>
							<a class="table-btn text-white" href="javascript:void(0);" data-toggle="tooltip" data-original-title="打印"><i class="layui-icon layui-icon-print"></i></a>
							<a class="table-btn text-success" href="javascript:void(0);" data-toggle="tooltip" data-original-title="已审核"><i class="layui-icon layui-icon-vercode"></i></a>
							<span>申请人：吴晶晶</span>
							<span>采购人：吴晶晶</span>
							<span>审批人：吴晶晶</span>
						</div>
						<div class="layui-col-md3">
							'.MaterialModel::status_bar_tag($v['status']).'
						</div>
						<div class="layui-col-md1">
							<span>'.MaterialModel::$status[$v['status']].'</span>
						</div>
						
						
						<div class="layui-col-md12 new-table-head-flex text-black">
                            <span>采购形式：关联采购</span>
                            <span>采购内容：'.$v['type_name'].'</span>
                            <span>采购数量：'.$v['number'].'(kg)</span>
                            <span>订单状态：'.MaterialModel::$urgent_status[$v['urgent_status']].'</span>
                            <span>采购日期：'.date('Y-m-d',$v['create_time']).'</span>
                            <span>预估到货：'.date('Y-m-d',$v['address_time']).'<a class="btn btn-primary new-table-body-show" style="float: right;" data-id="'.$v['id'].'">点击展开</a></span>
                            
						</div>
					';

                $v['title'] = $html;

                $v['title2'] = $this->ajaxGoodsList($v);

                return $v;
            })
        ;

        $css = "<style>
                .dch-ul {width: 100%;padding: 0;margin: 0;}
                .dch-li {list-style-type: none;}
                .dch-bottom {border-bottom: 1px solid #f0f0f0;}
                .new-table-body {display: none}
                
            </style>";
        //JS
        $js = '<script type="text/javascript">
                $(function(){
                    $(".new-table-body-show").click(function() {
                        var id = $(this).attr("data-id");
                        $(".new-table-body").hide();
                        $(".new-table-body[data-content=\'"+id+"\']").show();
                    });
                    $(".new-table-body-show").eq(0).click();
                });
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('我发起的采购单') // 页面标题
            ->setTableName('wh_material') // 设置表名
            //->setExtraHtml($this->_top_html,'block_top')
            ->hideCheckbox()
            ->setSearchArea([
                ['select:1', 'm.status', '采购状态', 'eq','',MaterialModel::$status],
                //['select:2', 'm.supplier_id', '供应商', 'eq','',SupplierModel::getGroup()],
                ['select:1', 'm.type_pid', '采购类型', 'eq','',StockTypeModel::getGroup()],
                ['text:2', 'm.material_sn', '采购单号', 'like'],
                ['daterange:2', 'm.create_time', '采购日期'],
            ])
            ->addTrClass('hidden-remove','title','<>','')
            ->hideColumn('title','remove')
            ->addColumns([ // 批量添加列
                ['title', '','table_head'],
                ['title2', '','table_body'],
            ])
            ->setExtraCss($css)
            ->setExtraJs($js)
            //->addTopButton('selectOrder',['title' => '新增采购单','href' => url('selectOrder'),'icon'=>'','class'=>'btn btn-primary'],['area' => ['780px', '40%'], 'title' => ['新增采购单', 'font-size:24px;text-align: center;']])
            ->addTopButton('add2',['title' => '直接新增采购单','href' => url('add',['is_order_color'=>0,'type_pid'=>1]),'icon'=>'','class'=>'btn btn-primary'])
            ->addTopButton('add',['title' => '新增采购单','href' => url('add',['type_pid'=>1]),'icon'=>'','class'=>'btn btn-primary'])
            ->addTopButton('delete',['title' => '删除','icon'=>'','class'=>'btn bg-info-light ajax-post confirm'])
            ->addRightButton('add', ['title' => '编辑', 'href' => url('add', [ 'id' => '__id__']), 'icon' => ''])
            //->addRightButton('show', ['title' => '查看', 'href' => url('add', [ 'id' => '__id__']), 'icon' => ''])
            ->addRightButton('showPrint',['title' => '导出','href' => url('showPrint',['id'=>'__id__','print'=>'2']),'class'=>'btn bg-info-light disable-dch','icon'=>'','target'=>'_blank'])
            ->addRightButton('showPrint',['title' => '打印','href' => url('showPrint',['id'=>'__id__','print'=>'1']),'class'=>'btn bg-info-light disable-dch','icon'=>'','target'=>'_blank'])
            ->addRightButton('codePrint',['title' => '打印条码','href' => url('wh/stock/codePrint',['material_id' => '__id__','page'=>1]),'class'=>'btn bg-info-light disable-dch','icon'=>''],['area' => ['780px', '90%'], 'title' => ['正在打印中...', 'font-size:24px;text-align: center;']])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'title'  => 20,
                'title2'  => 20,
                //'note'  => 300,
                //'mobile'  => 80,
                //'sales_mobile'  => 80,
                //'address'  => 150,
                //'status'  => 280,
            ])
            ->fetch(); // 渲染模板
    }

    /**
     * 待审核采购单列表页
     * @return mixed
     */
    public function myVerify()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        cookie('__forward2__', $_SERVER['REQUEST_URI']);

        $input = input();
        if(empty($input))return $this->index(2);

        $stock_type = input('stock_type');
        $type_pid = $stock_type;

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['m.type_pid','=',$type_pid];
        $map[] = ['m.status','=',0];

        // 数据列表
        $data_list = Db::name('wh_material')
            ->alias('m')
            ->field('m.*,s.title_abb as supplier_name,u.nickname,t.title as type_name')
            ->leftJoin('wh_supplier s','m.supplier_id=s.id')
            ->leftJoin('admin_user u','m.uid=u.id')
            ->leftJoin('wh_stock_type t','m.type_pid=t.id')
            ->where($map)
            ->order('m.id desc')
            ->paginate()
            ->each(function ($v){

                //采购单信息
                $html = '
						<div class="layui-col-md8">
							<span>采购单编码：'.$v['material_sn'].' </span>
							<a class="table-btn text-white" href="javascript:void(0);" data-toggle="tooltip" title="删除"><i class="layui-icon layui-icon-delete"></i></a>
							<a class="table-btn text-white" href="javascript:void(0);" data-toggle="tooltip" data-original-title="编辑"><i class="layui-icon layui-icon-edit"></i></a>
							<a class="table-btn text-white" href="javascript:void(0);" data-toggle="tooltip" data-original-title="打印"><i class="layui-icon layui-icon-print"></i></a>
							<a class="table-btn text-success" href="javascript:void(0);" data-toggle="tooltip" data-original-title="已审核"><i class="layui-icon layui-icon-vercode"></i></a>
							<span>申请人：吴晶晶</span>
							<span>采购人：吴晶晶</span>
							<span>审批人：吴晶晶</span>
						</div>
						<div class="layui-col-md3">
							'.MaterialModel::status_bar_tag($v['status']).'
						</div>
						<div class="layui-col-md1">
							<span>'.MaterialModel::$status[$v['status']].'</span>
						</div>
						
						
						<div class="layui-col-md12 new-table-head-flex text-black">
                            <span>采购形式：关联采购</span>
                            <span>采购内容：'.$v['type_name'].'</span>
                            <span>采购数量：'.$v['number'].'(kg)</span>
                            <span>订单状态：'.MaterialModel::$urgent_status[$v['urgent_status']].'</span>
                            <span>采购日期：'.date('Y-m-d',$v['create_time']).'</span>
                            <span>预估到货：'.date('Y-m-d',$v['address_time']).'<a class="btn btn-primary new-table-body-show" style="float: right;" data-id="'.$v['id'].'">点击展开</a></span>
                            
						</div>
					';

                $v['title'] = $html;

                $v['title2'] = $this->ajaxGoodsList($v);

                return $v;
            })
        ;

        $css = "<style>
                .dch-ul {width: 100%;padding: 0;margin: 0;}
                .dch-li {list-style-type: none;}
                .dch-bottom {border-bottom: 1px solid #f0f0f0;}
                .new-table-body {display: none}
                
            </style>";
        //JS
        $js = '<script type="text/javascript">
                $(function(){
                    $(".new-table-body-show").click(function() {
                        var id = $(this).attr("data-id");
                        $(".new-table-body").hide();
                        $(".new-table-body[data-content=\'"+id+"\']").show();
                    });
                    $(".new-table-body-show").eq(0).click();
                });
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('采购申请') // 页面标题
            ->setTableName('wh_material') // 设置表名
            //->setExtraHtml($this->_top_html,'block_top')
            ->hideCheckbox()
            ->setSearchArea([
                ['select:1', 'm.status', '采购状态', 'eq','',MaterialModel::$status],
                //['select:2', 'm.supplier_id', '供应商', 'eq','',SupplierModel::getGroup()],
                ['select:1', 'm.type_pid', '采购类型', 'eq','',StockTypeModel::getGroup()],
                ['text:2', 'm.material_sn', '采购单号', 'like'],
                ['daterange:2', 'm.create_time', '采购日期'],
            ])
            ->addTrClass('hidden-remove','title','<>','')
            ->hideColumn('title','remove')
            ->addColumns([ // 批量添加列
                ['title', '','table_head'],
                ['title2', '','table_body'],
            ])
            ->setExtraCss($css)
            ->setExtraJs($js)
            ->addRightButton('notDisable',['title' => '审核不通过','href' => url('notDisable',['id' => '__id__','field'=>'status']),'class'=>'btn bg-danger-light','icon'=>''],['area' => ['780px', '50%'], 'title' => ['审核不通过原因', 'font-size:24px;text-align: center;']])
            ->addRightButton('backEnable',['title' => '审核通过','href' => url('backEnable',['id' => '__id__']).'?fieldv=status|1','class'=>'btn bg-info-light ajax-get','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'title'  => 20,
                'title2'  => 20,
            ])
            ->fetch(); // 渲染模板
    }

    //AJAX获取采购单明细
    public function ajaxGoodsList($material){

        $list = [];

        $type_pid = $material['type_pid'];

        //采购单明细
        $goods_list = Db::name('wh_material_goods')
            ->alias('g')
            ->field("g.*,s.number as sum_number,s.num as sum_num,t.title as type_name,o.engineering,'{$material['supplier_name']}' as supplier_name")
            ->leftJoin('wh_stock_type t','t.id=g.type_id')
            ->leftJoin('wh_stock s','s.id=g.stock_sn')
            ->leftJoin('mill_order o','o.id=g.order_id')
            ->where(['material_id'=>$material['id']])
            ->group('stock_sn')
            ->order('id asc')
            ->select();

        if(!empty($goods_list)){
            $i = 1;
            foreach ($goods_list as &$v){

                //序号
                $v['sort'] = $i.MaterialModel::urgent_status_color($v['status'],MaterialModel::$status[$v['status']]);
                //二维码
                $v['stock_sn_img'] = '<div class="js-gallery"><img class="layui-img" style="width: 20px" src="'.plugin_url('Qrcode/Qrcode/generate', ['text' => $v['stock_sn']]).'" /></div>';
                //打印标签
                $url_parm = ['stock_sn'=>$v['stock_sn']];
                $url = url('wh/stock/codePrint',$url_parm)."?_pop=1";
                $layer = '{&quot;area&quot;:[&quot;780px&quot;,&quot;90%&quot;],&quot;title&quot;:[&quot;物料标签&quot;,&quot;font-size:24px;text-align: center;&quot;]}';

                $v['stock_sn2']= '<a class="btn btn-primary disable-dch pop" href="'.$url.'" data-layer="'.$layer.'" _tag="archivesPrint" data-toggle="tooltip" data-original-title="打印"><i class="layui-icon layui-icon-print"></i></a>';

                $i++;
            }
        }
        switch ($type_pid){
            //油漆库
            case in_array($type_pid,ColorModel::$type_pid_arr):

                //显示采购单工程定色数据
                $table['data'] = Db::name('wh_material_goods')
                    ->alias('g')
                    ->field("c.*,'' as sum_number,cc.nickname,cc.sales,cc.back,o.engineering,t.title as type_name,'{$material['supplier_name']}' as supplier_name")
                    ->leftJoin('wh_stock_type t','t.id=g.type_id')
                    ->leftJoin('wh_order_color c','c.id=g.order_color_id')
                    ->leftJoin('mill_order o','o.id=c.order_id')
                    ->leftJoin('mill_client cc','cc.id=o.client_id')
                    ->where(['material_id'=>$material['id']])
                    ->group('stock_sn')
                    ->order('order_id asc,id asc')
                    ->select();

                //显示合计
                $table['sum'] = [
                    'title'     =>  '小计',
                    'group'     =>  'order_id',
                    'field'     =>  ['sug_number','number']
                ];

                //列表表头
                $table['head'] = [
                    // 批量添加列
                    'archives_sn'           =>  ['archives_sn', '档案编号'],
                    'nickname'              =>  ['nickname', '客户'],
                    'engineering'           =>  ['engineering', '工程'],
                    'sales'                 =>  ['sales', '业务代表'],
                    'back'                  =>  ['back', '内勤'],
                    'supplier_color'        =>  ['supplier_color', '颜色编号'],
                    'color'                 =>  ['color', '颜色名称'],
                    'color_sn'              =>  ['color_sn', '系统编号'],
                    'type_name'             =>  ['type_name', '类别'],
                    'color_type_id'         =>  ['color_type_id', '类型',ColorModel::getColorType()],
                    'quality'               =>  ['quality', '属性',ColorModel::getQuality()],
                    'heat'                  =>  ['heat', '油温',MaterialModel::$heat],
                    'supplier_name'         =>  ['supplier_name', '供应商'],
                    'sum_number'            =>  ['sum_number', '当前库存(kg)'],
                    'row_area'              =>  ['row_area', '采购面积'],
                    'sug_number'            =>  ['sug_number', '建议量(kg)'],
                    'number'                =>  ['number', '采购量(kg)'],
                ];

                $list[] = $table;

                //采购单明细
                //列表表头
                $table['head'] = [
                    // 批量添加列
                    'sort'                  =>  ['sort', '序号'],
                    'supplier_color'        =>  ['supplier_color', '颜色编号'],
                    'material_name'         =>  ['material_name', '颜色名称'],
                    'color_sn'              =>  ['color_sn', '系统编号'],
                    'type_name'             =>  ['type_name', '类别'],
                    'color_type_id'         =>  ['color_type_id', '类型',ColorModel::getColorType()],
                    'quality'               =>  ['quality', '属性',ColorModel::getQuality()],
                    'heat'                  =>  ['heat', '油温',MaterialModel::$heat],
                    'supplier_name'         =>  ['supplier_name', '供应商'],
                    'sum_number'            =>  ['sum_number', '当前库存(kg)'],
                    'row_area'              =>  ['row_area', '采购面积'],
                    'sug_number'            =>  ['sug_number', '建议量(kg)'],
                    'number'                =>  ['number', '采购量(kg)'],
                    'price'                 =>  ['price', '采购单价'],
                    'sum_price'             =>  ['sum_price', '采购金额'],
                    'stock_sn_img'          =>  ['stock_sn_img', '二维码'],
                    'stock_sn2'             =>  ['stock_sn2', '打印标签'],
                ];


                //采购单明细
                $table['data'] = $goods_list;

                //显示合计
                $table['sum'] = [
                    'title'     =>  '合计',
                    'field'     =>  ['sug_number','number','sum_price']
                ];

                break;
            //铝卷
            case 4:

                //列表表头
                $table['head'] = [
                    // 批量添加列
                    'sort'                  =>  ['sort', '序号'],
                    'type_name'             =>  ['type_name', '系别'],
                    'material_name'         =>  ['material_name', '名称'],
                    'model'                 =>  ['model', '型号规格'],
                    'quality'               =>  ['quality', '材质',ColorModel::getQuality()],
                    'supplier_name'         =>  ['supplier_name', '供应商'],
                    'lot_sn'                =>  ['lot_sn', '批号'],
                    'sum_num'               =>  ['sum_num', '库存数量(C)'],
                    'sum_number'            =>  ['sum_number', '库存重量(kg)'],
                    'engineering'           =>  ['engineering', '关联工程'],
                    'num'                   =>  ['num', '采购数量(C)'],
                    'number'                =>  ['number', '采购重量(kg)'],
                    'sum_price'             =>  ['sum_price', '采购金额'],
                    'stock_sn_img'          =>  ['stock_sn_img', '二维码'],
                    'stock_sn2'             =>  ['stock_sn2', '打印标签'],
                ];


                //采购单明细
                $table['data'] = $goods_list;

                //显示合计
                $table['sum'] = [
                    'title'     =>  '合计',
                    'field'     =>  ['num','number','sum_price']
                ];

                break;
            //铝板
            case 5:

                //列表表头
                $table['head'] = [
                    // 批量添加列
                    'sort'                  =>  ['sort', '序号'],
                    'type_name'             =>  ['type_name', '系别'],
                    'material_name'         =>  ['material_name', '名称'],
                    'model'                 =>  ['model', '型号规格'],
                    'quality'               =>  ['quality', '材质',ColorModel::getQuality()],
                    'supplier_name'         =>  ['supplier_name', '供应商'],
                    'lot_sn'                =>  ['lot_sn', '批号'],
                    'sum_num'               =>  ['sum_num', '库存数量(张)'],
                    'sum_number'            =>  ['sum_number', '库存重量(kg)'],
                    'engineering'           =>  ['engineering', '关联工程'],
                    'num'                   =>  ['num', '采购数量(张)'],
                    'number'                =>  ['number', '采购重量(kg)'],
                    'sum_price'             =>  ['sum_price', '采购金额'],
                    'stock_sn_img'          =>  ['stock_sn_img', '二维码'],
                    'stock_sn2'             =>  ['stock_sn2', '打印标签'],
                ];


                //采购单明细
                $table['data'] = $goods_list;

                //显示合计
                $table['sum'] = [
                    'title'     =>  '合计',
                    'field'     =>  ['num','number','sum_price']
                ];

                break;
            //型材
            case 3:

                //列表表头
                $table['head'] = [
                    // 批量添加列
                    'sort'                  =>  ['sort', '序号'],
                    'type_name'             =>  ['type_name', '系别'],
                    'material_name'         =>  ['material_name', '名称'],
                    'model'                 =>  ['model', '型号规格'],
                    'long'                  =>  ['long', '长度(m)'],
                    'supplier_name'         =>  ['supplier_name', '供应商'],
                    'unit'                  =>  ['unit', '单位'],
                    'sum_number'            =>  ['sum_number', '库存重量(kg)'],
                    'sum_num'               =>  ['sum_num', '库存数量'],
                    'engineering'           =>  ['engineering', '关联工程'],
                    'num'                   =>  ['num', '采购数量'],
                    'number'                =>  ['number', '采购重量(kg)'],
                    'sum_price'             =>  ['sum_price', '采购金额'],
                    'stock_sn_img'          =>  ['stock_sn_img', '二维码'],
                    'stock_sn2'             =>  ['stock_sn2', '打印标签'],
                ];


                //采购单明细
                $table['data'] = $goods_list;

                //显示合计
                $table['sum'] = [
                    'title'     =>  '合计',
                    'field'     =>  ['num','number','sum_price']
                ];

                break;
            //化工
            case 2:

                //列表表头
                $table['head'] = [
                    // 批量添加列
                    'sort'                  =>  ['sort', '序号'],
                    'type_name'             =>  ['type_name', '系别'],
                    'material_name'         =>  ['material_name', '名称'],
                    'model'                 =>  ['model', '规格'],
                    'model2'                =>  ['model2', '型号'],
                    'supplier_name'         =>  ['supplier_name', '供应商'],
                    'unit'                  =>  ['unit', '单位'],
                    'sum_number'            =>  ['sum_number', '库存重量(kg)'],
                    'sum_num'               =>  ['sum_num', '库存数量'],
                    'engineering'           =>  ['engineering', '关联工程'],
                    'num'                   =>  ['num', '采购数量'],
                    'number'                =>  ['number', '采购重量(kg)'],
                    'price'                 =>  ['sum_price', '采购单价'],
                    'sum_price'             =>  ['sum_price', '采购金额'],
                    'stock_sn_img'          =>  ['stock_sn_img', '二维码'],
                    'stock_sn2'             =>  ['stock_sn2', '打印标签'],
                ];


                //采购单明细
                $table['data'] = $goods_list;

                //显示合计
                $table['sum'] = [
                    'title'     =>  '合计',
                    'field'     =>  ['num','number','sum_price']
                ];

                break;
            //生产物资
            case 6:
                //办公物资
            case 7:
                //其他
            default:

            //列表表头
            $table['head'] = [
                // 批量添加列
                'sort'                  =>  ['sort', '序号'],
                'type_name'             =>  ['type_name', '系别'],
                'material_name'         =>  ['material_name', '名称'],
                'model'                 =>  ['model', '规格'],
                'model2'                =>  ['model2', '型号'],
                'supplier_name'         =>  ['supplier_name', '供应商'],
                'unit'                  =>  ['unit', '单位'],
                'sum_number'            =>  ['sum_number', '库存重量(kg)'],
                'sum_num'               =>  ['sum_num', '库存数量'],
                'engineering'           =>  ['engineering', '关联工程'],
                'num'                   =>  ['num', '采购数量'],
                'number'                =>  ['number', '采购重量(kg)'],
                'price'                 =>  ['sum_price', '采购单价'],
                'sum_price'             =>  ['sum_price', '采购金额'],
                'stock_sn_img'          =>  ['stock_sn_img', '二维码'],
                'stock_sn2'             =>  ['stock_sn2', '打印标签'],
            ];


            //采购单明细
            $table['data'] = $goods_list;

            //显示合计
            $table['sum'] = [
                'title'     =>  '合计',
                'field'     =>  ['num','number','sum_price']
            ];

                break;
        }

        $list[] = $table;

        return $list;

    }

    /**
     * 采购单明细
     */
    public function goodsList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $stock_type = input('stock_type',$this->_type_id);
        if(empty($stock_type))$stock_type = StockTypeModel::getTypePidFirst();
        $list_tab = StockTypeModel::getTabNav('goodsList');
        foreach ($list_tab as $tlk=>$tlv){

            if($tlk == 8){
                unset($list_tab[$tlk]);
                continue;
            }
        }

        $type_pid = Db::name('wh_stock_type')->where(['id'=>$stock_type])->value('pid');

        $supplier_list = SupplierModel::getGroup(0,$type_pid,'title_abb');

        // 获取查询条件
        $map = $this->getMap();
        $map2 = '';
        foreach ($map as $mk=>$mv){
            if(!empty($mv[0]) && $mv[0] == 's.model' && !empty($mv[2])){
                $arr = explode(',',trim($mv[2],'%'));
                $map2 .= " and (";
                foreach ($arr as $ak=>$av){
                    if(!empty($ak))$map2 .= " or ";
                    $map2 .= " s.model like '%{$av}%' ";
                }
                $map2 .= ")";
                unset($map[$mk]);
            }
            elseif(!empty($mv[0]) && $mv[0] == 'is_number' && !empty($mv[2])){
                $is_number = $mv[2];
                //无库存
                if($is_number == 1){
                    $map2 .= " and s.number = 0";
                }
                //有库存
                if($is_number == 2){
                    $map2 .= " and s.number > 0";
                }
                unset($map[$mk]);
            }
        }
        $map2 = trim(trim($map2),'and');
        $map = array_merge($map);
        $map[] = ['g.type_id','=',$stock_type];
        $map[] = ['g.status','>=',1];
        // 数据列表
        $data_list = Db::name('wh_material_goods')
            ->alias('g')
            ->field('g.*,g.number as number2,g.num as num2,o.archives_bill_time,o.engineering,o.batch,t.title as type_pname,tt.title as type_name,ss.title_abb as supplier_name,c.archives_number,c.archives_color,s.number as sum_number,s.num as sum_num')
            ->leftJoin('mill_order o','o.id=g.order_id')
            ->leftJoin('wh_order_color c','c.id=g.order_color_id')
            ->leftJoin('wh_stock s','s.stock_sn=g.stock_sn')
            ->leftJoin('wh_stock_type t','t.id=g.type_pid')
            ->leftJoin('wh_stock_type tt','tt.id=g.type_id')
            ->leftJoin('wh_supplier ss','ss.id=g.supplier_id')
            ->where($map)
            ->where($map2)
            ->order('g.material_id desc,g.stock_sn desc,g.archives_sn asc')
            ->paginate()
            ->each(function ($v){

                //采购数量
                $v['num'] = Db::name('wh_material_goods')->where(['material_id'=>$v['material_id'],'stock_sn'=>$v['stock_sn']])->sum('num');
                $v['number'] = Db::name('wh_material_goods')->where(['material_id'=>$v['material_id'],'stock_sn'=>$v['stock_sn']])->sum('number');
                $v['num'] = "<div data-m-id='{$v['material_id']}{$v['stock_sn']}'>{$v['num']}</div>";
                $v['number'] = "<div data-m-id='{$v['material_id']}{$v['stock_sn']}'>{$v['number']}</div>";

                //收货情况
                $v['number2'] = Db::name('wh_stock_log')->where(['material_sn'=>$v['material_sn'],'stock_sn'=>$v['stock_sn']])->sum('number');
                $v['num2'] = "<div data-m-id='{$v['material_id']}{$v['stock_sn']}'>{$v['num']}</div>";
                $v['number2'] = "<div data-m-id='{$v['material_id']}{$v['stock_sn']}'>{$v['number2']}</div>";
                //面积表总数量
                $v['status_sum'] = Db::name('mill_order_archives')->where(['color'=>$v['archives_color']])->sum('number');
                //钣金数量
                $give_where = [['g.order_id','=',$v['order_id']],['a.color','=',$v['archives_color']]];
                $v['status2_sum'] = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where($give_where)
                    ->where([['g.status','>=',2]])
                    ->count('g.id');
                if($v['status2_sum'] == $v['status_sum'])$v['status2_sum'] = '<span class="label label-info">已完成</span>';
                else $v['status2_sum'] = '<span class="label label-danger">未完成</span>';
                //喷涂数量
                $give_where = [['g.order_id','=',$v['order_id']],['a.color','=',$v['archives_color']]];
                $v['status3_sum'] = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where($give_where)
                    ->where([['g.status','>=',3]])
                    ->count('g.id');
                if($v['status3_sum'] == $v['status_sum'])$v['status3_sum'] = '<span class="label label-info">已完成</span>';
                else $v['status3_sum'] = '<span class="label label-danger">未完成</span>';

                return $v;
            })
        ;

        //合计：库存，采购数量，采购重量，收货数量，收货重量
        //采购，库存去重求和：SUM(DISTINCT case when s.id then s.number else 0 end)
        $total = Db::name('wh_material_goods')
            ->alias('g')
            ->field('sum(g.num) as num,sum(g.number) as number,GROUP_CONCAT(DISTINCT s.id) as stock_ids')
            ->leftJoin('mill_order o','o.id=g.order_id')
            ->leftJoin('wh_stock s','s.stock_sn=g.stock_sn')
            ->where($map)
            ->where($map2)
            ->find();
        //收货
        $total1 = Db::name('wh_material_goods')
            ->alias('g')
            ->field('sum(g.num) as num,sum(g.number) as number')
            ->leftJoin('mill_order o','o.id=g.order_id')
            ->where($map)
            ->where($map2)
            ->where('g.status>=2')
            ->find();
        //库存
        $total2 = Db::name('wh_stock')
            ->field('sum(num) as num,sum(number) as number')
            ->where([['id','in',$total['stock_ids']],['number','>',0]])
            ->find();
        $total_str = "采购数量：{$total['num']}(次)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;采购重量：{$total['number']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;收货数量：{$total1['num']}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;收货重量：{$total1['number']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;库存数量：{$total2['num']}(件)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp库存重量：{$total2['number']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp";

        //搜索头
        $search_area = [
            ['select:2', 'g.supplier_id', '供应商', 'eq','',$supplier_list],
            ['text:1', 'g.model', '供应商色号', 'like'],
            ['text:1', 'o.engineering', '工程名称', 'like'],
            ['text:1', 'o.archives_sn', '档案号', 'like'],
            ['text:1', 'g.model', '规格型号', 'like'],
            ['text:1', 'g.lot_sn', '批号', 'like'],
            ['select:1', 'g.status', '收货状态', 'eq','',MaterialModel::$status],
            ['text:1', 'g.material_sn', '采购单号', 'like'],
            ['select:1', 'is_number', '有无库存', 'eq','',[1=>'无库存',2=>'有库存']],
            ['daterange:2', 'g.create_time', '采购日期'],
        ];

        $tab_js = '';
        //列表表头
        switch ($type_pid){
            //油漆库
            case in_array($type_pid,ColorModel::$type_pid_arr):
                unset($search_area[4]);
                unset($search_area[5]);
                unset($search_area[8]);

                $tab_column = [
                    // 批量添加列
                    'archives_bill_time'          =>  ['archives_bill_time', '下单日期','date','','','bg-color-1'],
                    'create_time'           =>  ['create_time', '采购日期','date','','','bg-color-1'],
                    'material_sn'           =>  ['material_sn', '采购单号','','','','bg-color-1'],
                    'engineering'           =>  ['engineering', '工程名称','','','','bg-color-1'],
                    'archives_sn'           =>  ['archives_sn', '档案号','','','','bg-color-1'],
                    'batch'                 =>  ['batch', '批次','','','','bg-color-1'],
                    'archives_number'       =>  ['archives_number', '数量','','','','bg-color-1'],
                    'row_area'              =>  ['row_area', '面积(M²)','','','','bg-color-1'],
                    'material_name'         =>  ['material_name', '颜色名称'],
                    'supplier_color'        =>  ['supplier_color', '供应商色号'],
                    'color_sn'              =>  ['color_sn', '自编号'],
                    'color_type_id'         =>  ['color_type_id', '喷涂类型',ColorModel::getColorType()],
                    'sum_number'            =>  ['sum_number', '库存(KG)'],
                    'supplier_name'         =>  ['supplier_name', '供应商'],
                    'number'                =>  ['number', '采购数量','','','','bg-color-2'],
                    'status'                =>  ['status', '收货状态',MaterialModel::$status,'','','bg-color-2'],
                    'number2'               =>  ['number2', '收货数量','','','','bg-color-2'],
                    'status2_sum'           =>  ['status2_sum', '钣金情况','','','','bg-color-2'],
                    'status3_sum'           =>  ['status3_sum', '喷涂情况','','','','bg-color-2'],
                ];
                $table_head_html = '<tr><th colspan="8">基本信息</th><th class="bg-color-2" colspan="6">颜色信息</th><th colspan="5">采购信息</th></tr>';

                $total_str = "采购数量：{$total['number']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;收货数量：{$total1['number']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;库存数量：{$total2['number']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp";

                $tab_js = '<script type="text/javascript">
                        //单元格合并
                        jQuery.fn.rowspan = function(colIdx=0) {
                            var that;
                            return this.each(function(row) {
                                $("td:eq(" + colIdx + ")", this).filter(":visible").each(function(col) {
                                    if (that != null && $(this).html() == $(that).html()) {
                                        rowspan = $(that).attr("rowSpan");
                                        if (rowspan == undefined) {
                                            $(that).attr("rowSpan", 1);
                                            rowspan = $(that).attr("rowSpan");
                                        }
                                        rowspan = Number(rowspan) + 1;
                                        $(that).attr("rowSpan", rowspan);
                                        $(this).hide();
                                    } else {
                                        that = this;
                                    }
                                });
                                
                            
                            });
                        };
                        $(function() {
                            //要合并的列序号，后面数字是第几列
                            $("#builder-table-main").find("tr").rowspan(14);
                            $("#builder-table-main").find("tr").rowspan(16);
                        });
                    </script>';

                break;
            //铝卷
            case 4:
                unset($search_area[1]);
                unset($search_area[2]);
                unset($search_area[3]);

                $tab_column = [
                    // 批量添加列
                    'material_sn'           =>  ['material_sn', '采购单号','','','','bg-color-1'],
                    'create_time'           =>  ['create_time', '采购日期','date','','','bg-color-1'],
                    'material_name'         =>  ['material_name', '物料名称','','','','bg-color-1'],
                    'type_name'             =>  ['type_name', '系列(类别)','','','','bg-color-1'],
                    'supplier_name'         =>  ['supplier_name', '供应商','','','','bg-color-1'],
                    'model'                 =>  ['model', '规格型号','','','','bg-color-1'],
                    'quality'               =>  ['quality', '材质(合金状态)',ColorModel::getQuality(),'','','bg-color-1'],
                    'lot_sn'                =>  ['lot_sn', '批号','','','','bg-color-1'],
                    'sum_number'            =>  ['sum_number', '库存(KG)','','','','bg-color-1'],
                    'number'                =>  ['number', '采购数量'],
                    'status'                =>  ['status', '收货状态',MaterialModel::$status],
                    'number2'               =>  ['number2', '收货数量'],
                ];
                $table_head_html = '<tr><th colspan="9">基本信息</th><th class="bg-color-2" colspan="3">采购信息</th></tr>';

                $total_str = "采购数量：{$total['number']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;收货数量：{$total1['number']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;库存数量：{$total2['number']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp";
                break;
            //铝板
            case 5:
                unset($search_area[1]);
                unset($search_area[2]);
                unset($search_area[3]);

                $tab_column = [
                    // 批量添加列
                    'material_sn'           =>  ['material_sn', '采购单号','','','','bg-color-1'],
                    'create_time'           =>  ['create_time', '采购日期','date','','','bg-color-1'],
                    'material_name'         =>  ['material_name', '物料名称','','','','bg-color-1'],
                    'type_name'             =>  ['type_name', '系列(类别)','','','','bg-color-1'],
                    'supplier_name'         =>  ['supplier_name', '供应商','','','','bg-color-1'],
                    'model'                 =>  ['model', '规格型号','','','','bg-color-1'],
                    'quality'               =>  ['quality', '材质(合金状态)',ColorModel::getQuality(),'','','bg-color-1'],
                    'lot_sn'                =>  ['lot_sn', '批号','','','','bg-color-1'],
                    'sum_num'               =>  ['sum_num', '库存数量(张)','','','','bg-color-1'],
                    'sum_number'            =>  ['sum_number', '库存重量(KG)','','','','bg-color-1'],
                    'num'                   =>  ['num', '采购数量(张)'],
                    'number'                =>  ['number', '采购重量(KG)'],
                    'status'                =>  ['status', '收货状态',MaterialModel::$status],
                    'num2'                  =>  ['num2', '收货数量(张)'],
                    'number2'               =>  ['number2', '收货重量(KG)'],
                ];
                $table_head_html = '<tr><th colspan="10">基本信息</th><th class="bg-color-2" colspan="5">采购信息</th></tr>';

                $total_str = "采购数量：{$total['num']}(张)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;采购重量：{$total['number']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;收货数量：{$total1['num']}(张)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;收货重量：{$total1['number']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;库存数量：{$total2['num']}(张)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp库存重量：{$total2['number']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp";
                break;
            //型材
            case 3:
            //化工
            case 6:
                //其他
            case 7:
                unset($search_area[1]);
                unset($search_area[2]);
                unset($search_area[3]);
                unset($search_area[5]);

                $tab_column = [
                // 批量添加列
                'material_sn'           =>  ['material_sn', '采购单号','','','','bg-color-1'],
                'create_time'           =>  ['create_time', '采购日期','date','','','bg-color-1'],
                'material_name'         =>  ['material_name', '产品名称','','','','bg-color-1'],
                'supplier_name'         =>  ['supplier_name', '供应商','','','','bg-color-1'],
                //'long'                  =>  ['long', '长度(M)','','','','bg-color-1'],
                //'num'                   =>  ['num', '数量'],
                //'number'                =>  ['number', '重量(吨)'],
                'sum_num'               =>  ['sum_num', '库存数量(张)','','','','bg-color-1'],
                'sum_number'            =>  ['sum_number', '库存重量(KG)','','','','bg-color-1'],
                'create2_time'          =>  ['create_time2', '订单日期','date'],
                'num'                   =>  ['num', '采购数量(张)'],
                'number'                =>  ['number', '采购重量(KG)'],
                'status'                =>  ['status', '收货状态',MaterialModel::$status],
                'num2'                  =>  ['num2', '收货数量(张)'],
                'number2'               =>  ['number2', '收货重量(KG)'],
            ];
                $table_head_html = '<tr><th colspan="6">基本信息</th><th class="bg-color-2" colspan="6">采购信息</th></tr>';
                break;
        }

        $css = "<style>
                #builder-table > th,td{font-size: 12px;}
                .table > thead > tr > th, .table > tbody > tr > th, .table > tfoot > tr > th {
                    padding: 8px;
                    font-size: 12px;
                    font-weight: 600;
                }
                .table-builder > tbody > tr > td {padding: 0 0 0 4px;}
                #builder-table-main {margin-bottom: -1px;}
                .table-builder, .table-bordered > thead > tr > .bg-color-1 {background: #fcca00;}
                .table-builder, .table-bordered > thead > tr > .bg-color-2 {background: #70b9eb;}
                .alert-dismissable{padding: initial;margin: inherit;}
            </style>";
        //JS
        $js = '
            <script type="text/javascript">
                $(function() {
                    $("#builder-table-wrapper").css("max-height","800px");
                    $("#builder-table-body").css("max-height","530px");
                    
                    var table_head_html = \''.$table_head_html.'\';
                    $("#builder-table-head table thead").html(table_head_html+$("#builder-table-head table thead").html());
                    $("#builder-table-right-head table thead").html(table_head_html+$("#builder-table-right-head table thead").html());
                    
                    //打印
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "采购单明细",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                    
                })
            </script>';
        $js .= $tab_js;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('采购单明细') // 页面标题
            ->setTableName('wh_material_goods') // 设置表名
            ->hideCheckbox()
            ->setPageTips($total_str,'info','topbtn')
            ->setTabNav($list_tab,$stock_type)
            ->setSearchArea($search_area)
            ->addColumns($tab_column)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn bg-info-light quality-print'])
            ->js('jquery.table2excel', 'common')
            ->setExtraCss($css)
            ->setExtraJs($js)
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'batch'  => 60,
                'archives_number'  => 50,
                'color_type_id'     => 60,
                'number'     => 60,
                'status'     => 60,
                'number2'     => 60,
                'status2_sum'     => 74,
                'status3_sum'     => 74,
            ],80)
            ->fetch(); // 渲染模板
    }

    /**
     * 审核
     */
    public function backEnable()
    {

        $id = input('param.id');
        $fieldv = input('param.fieldv');
        $fieldv = explode('|',$fieldv);
        if (false === MaterialModel::where('id', $id)->setField($fieldv[0], $fieldv[1])) {
            $this->error('审核失败，订单ID：'.$id);
        }
        //审核人员
        MaterialModel::where('id', $id)->setField($fieldv[0].'_verify_uid', UID);
        //审核时间
        MaterialModel::where('id', $id)->setField($fieldv[0].'_time', time());

        Db::name('wh_material_goods')->where(['material_id'=>$id])->update(['status'=>1]);

        $this->success('提交成功', null, '_parent_reload');
    }

    /**
     * 审核不通过
     */
    public function notDisable()
    {
        $field = input('param.field');
        if ($this->request->isPost()) {
            $data = input();
            $id = input('param.id');
            if (false === MaterialModel::where('id', $id)->setField($field, -1)) {
                $this->error('审核失败，订单ID：'.$id);
            }
            if(!empty($data[$field.'_note']))MaterialModel::where('id', $id)->setField($field.'_note', $data[$field.'_note']);
            //审核人员
            MaterialModel::where('id', $id)->setField($field.'_verify_uid', UID);

            $this->success('操作成功', null, '_parent_reload');
        }

        return ZBuilder::make('form')
            ->setPageTitle('审核不通过原因') // 页面标题
            ->addFormItem('hidden', 'id')
            ->addFormItems([ // 批量添加表单项
                ['textarea', $field.'_note', '[:请输入审核不通过原因]'],
            ])
            ->layout([$field.'_note'=>12])
            ->fetch();
    }

    /**
     * 导出采购单
     */
    public function showPrint(){

        $id = input('param.id');
        $print = input('print');

        $info = Db::name('wh_material')->where(['id'=>$id])->find();
        $info['is_order_color'] = $info['order_ids'];

        $type_pid = $info['type_pid'];

        if(!empty($info['order_ids']) && in_array($type_pid,ColorModel::$type_pid_arr)){
            if(!empty($order_ids))$info['order_ids'] = $order_ids;
            $info['order_color_ids'] = '';
            $info['lists'] = Db::name('mill_order')->where([['id','in',$info['order_ids']]])->select();
            foreach ($info['lists'] as &$v){
                //总面积
                $v['row_area'] = 0;
                $where = [
                    ['g.order_id','=',$v['id']],
                    ['g.material_id','=',$info['id']],
                ];
                $v['lists'] = Db::name('wh_material_goods')
                    ->alias('g')
                    ->field('g.*,o.archives_sn,o.engineering,s.title as supplier,st.title as type_name,ct.title as color_type_name')
                    ->leftJoin('mill_order o','g.order_id=o.id')
                    //->leftJoin('wh_order_color c','g.color_id=c.id')
                    ->leftJoin('wh_supplier s','g.supplier_id=s.id')
                    ->leftJoin('wh_stock_type st','g.type_id=st.id')
                    ->leftJoin('wh_supplier_color_type ct','g.color_type_id=ct.id')
                    ->where($where)
                    ->order('g.id asc')
                    ->select();
                foreach ($v['lists'] as &$vv){
                    //供应商
                    $v['supplier'] = $vv['supplier'];
                    $info['supplier_id'] = $vv['supplier_id'];
                    //总面积
                    $v['row_area'] += $vv['row_area'];
                    $info['row_area'] += $vv['row_area'];
                    //采购量
                    $info['number'] += $vv['number'];
                    //订单颜色ID
                    $info['order_color_ids'] .= ",{$vv['order_color_id']}";
                    //获取库存
                    $vv['sum_number'] = StockModel::getSumNumber($vv);
                };
            }
        }
        else {
            $info['lists'] = Db::name('wh_material_goods')->where([['material_id','=',$info['id']]])->select();
            foreach ($info['lists'] as &$v){
                //总面积
                if(empty($v['row_area']))$v['row_area'] = 0;
                //获取库存
                $v['sum_number'] = StockModel::getSumNumber($v);
                /*if($v['type_pid'] == 5){
                    $v['row_area2'] = $v['row_area'];
                    //理论重量
                    $v['kg'] = $v['long']*$v['high']*$v['row_area'];
                    //实际重量
                    $v['kg2'] = $v['long']*$v['high']*$v['row_area'];
                    //材质 order_id="+order_id+"&thickness="+
                    $type_text = floatval(Db::name('wh_stock_type')->where(['id'=>$v['type_id']])->value('title'));
                    $v['model_list'] = $this->getOrderArchives(['order_id'=>$v['order_id'],'thickness'=>$type_text,'re_type'=>1]);
                    foreach ($v['model_list'] as &$vv){
                        $vv['id'] = $vv['model'];
                        $vv['title'] = $vv['model'];
                        $vv['data_html'] = "data-row_area='{$vv['row_area']}'";
                    }
                }*/

            }
        }

        $info['stock_type'] = StockTypeModel::getGroup($type_pid);
        $info['supplier'] = SupplierModel::getGroup(0,$type_pid);
        $info['quality'] = ColorModel::getQuality($type_pid);
        $info['color_type'] = ColorModel::getColorType();
        $info['order'] = OrderModel::getList("CONCAT(engineering,' ',archives_sn,' ',batch)",['status'=>1]);
        $info['model_list'] = [];
        $info['order_color_ids'] = trim($info['order_color_ids'],',');

        $html = MaterialModel::toHtml($type_pid,$info,$print);

        if($print == 2)$html = str_replace('window.print();',"",$html);

        exit($html);
    }

    /**
     * 编辑厂家颜色
     */
    public function editColor(){

        $action = new Color();

        return $action->edit();
    }

    //根据厂家色号查找对应供应商
    public function supplierColorList(){

        $action = new Color();

        return $action->supplierColorList();
    }

    //根据厂家色号查找对应供应商
    public function getSupplier(){

        $action = new Color();

        return $action->getSupplier();
    }

    //AJAX类别列表
    public function getStockType(){

        $action = new Color();

        return $action->getStockType();
    }

}
